<?php

/*
 +-----------------------------------------------------------------------+
 | plugins/amavisdnewsql/amavisdnewsql.inc                                   |
 |                                                                       |
 | This file is part of the RoundCube Webmail client                     |
 | Copyright (C) 2008-2009, RoundCube Dev. - Switzerland                 |
 | Licensed under the GNU GPL                                            |
 |                                                                       |
 | PURPOSE:                                                              |
 |	 Provide functionality for user spamassassin settings modification   |
 |                                                                       |
 +-----------------------------------------------------------------------+
 | Author: Ben Leto                                                 |
 +-----------------------------------------------------------------------+
 | Requires: plugins/amavisdnewsql/config.inc.php                          |
 +-----------------------------------------------------------------------+

 $Id: $

*/

require_once('plugins/amavisdnewsql/config.inc.php');

$OUTPUT->set_pagetitle(rcube_label('amavisdnewsqlsettings'));
$OUTPUT->add_handler('useramavisdnewsql', 'rcmail_amavisdnewsql_form');
$OUTPUT->include_script('amavisdnewsql.js');
$OUTPUT->add_label('spamaddressexists', 'spamenteraddress', 'spamaddresserror', 'spamaddressdelete', 'enabled', 'disabled');
$OUTPUT->send('amavisdnewsql');

function rcmail_amavisdnewsql_form($attrib){
	global $amavisdnewsql_config;

	$blocks = $attrib['parts'] ? preg_split('/[\s,;]+/', strip_quotes($attrib['parts'])) : array('general','addresses');

	$amavis_db = new rcube_mdb2($amavisdnewsql_config['db_dsnw'], $amavisdnewsql_config['db_dsnr'], $amavisdnewsql_config['db_persistent']);
	$amavis_db->db_connect('r');

	

	// check DB connections and exit on failure
	if ($err_str = $amavis_db->is_error()) {
	  raise_error(array(
	    'code' => 603,
	    'type' => 'db',
	    'message' => $err_str), FALSE, TRUE);
	}

	//Create the Amavis Users in the DB
	$sql = sprintf("SELECT * FROM users WHERE username = '%s'", mysql_real_escape_string(valid_email($_SESSION['username'])) );
	$sql_result = $amavis_db->query($sql);
	if ($sql_result && $amavis_db->num_rows($sql_result) == 0){
		$sql = sprintf("INSERT INTO users (priority,policy_id,email,digest,username,retention) VALUES ('7','1','%s','WD','%s','14')", mysql_real_escape_string(valid_email($_SESSION['username'])), mysql_real_escape_string(valid_email($_SESSION['username'])));
		$amavis_db->query($sql);
		//Update Sequence 
		$amavis_db->query("UPDATE users_id_seq SET id = id+1");
	}	


	list($form_start, $form_end) = get_form_tags($attrib, 'save-amavisdnewsql');
	unset($attrib['form']);

	$out = $form_start;

	foreach ($blocks as $part) {
		$out .= rcmail_amavisdnewsql_block($part, $attrib, $amavis_db);
	}
	
	return $out . $form_end;
}

function rcmail_amavisdnewsql_block($part, $attrib, $amavis_db) {
	global $RCMAIL, $OUTPUT, $amavisdnewsql_config;

	//Get Amavis UserID based on roundcube Session Username
		$sql = sprintf("SELECT * FROM users WHERE username = '%s'", mysql_real_escape_string(valid_email($_SESSION['username'])) );
		$sql_result = $amavis_db->query($sql);
		if ($sql_result && $amavis_db->num_rows($sql_result) > 0){
			$sql_arr = $amavis_db->fetch_assoc($sql_result);
			$_SESSION['amavis_uid'] = $sql_arr['id'];
			$_SESSION['amavis_pid'] = $sql_arr['policy_id'];
		}
		//Get Tag and Kill Level
		$sql = sprintf("SELECT spam_tag2_level, spam_kill_level FROM policy WHERE id = '%d'", mysql_real_escape_string($_SESSION['amavis_pid']) );
		$sql_result = $amavis_db->query($sql);
		if ($sql_result && $amavis_db->num_rows($sql_result) > 0){
			$sql_arr = $amavis_db->fetch_assoc($sql_result);
			$_SESSION['amavis_taglvl'] = $sql_arr['spam_tag2_level'];
			$_SESSION['amavis_killlvl'] = $sql_arr['spam_kill_level'];
		}
		
	switch ($part)
	{
	// General tests
	case 'general':
		$table = new html_table(array('cols' => 2));
			
			//********** Set Tag Level
			$field_id = 'rcmfd_and-taglvl';
			$input_spamthres = new html_inputfield(array('name' => '_taglvl', 'id' => $field_id, 'value' => $_SESSION['amavis_taglvl'], 'style' => 'width:35px;'));
			

			$table->add('title', html::label($field_id, Q(rcube_label('and-taglvl'))));
			$table->add(null, $input_spamthres->show((float)$_SESSION['amavis_taglvl']));

			$table->add(array('colspan' => 2), Q(rcube_label('and-taglvl-exp')));
			$table->add_row();
			
			//********** Set Kill Level
			$field_id = 'rcmfd_and-killlvl';
			$input_spamthres = new html_inputfield(array('name' => '_killlvl', 'id' => $field_id, 'value' => $_SESSION['amavis_killlvl'], 'style' => 'width:35px;'));
	
			//********** Policy ID
			$hidden_policy = new html_hiddenfield(array('name' => '_policyid', 'value' => $_SESSION['amavis_pid'] ));
			//********** Static Policy ID
			$hidden_spolicy = new html_hiddenfield(array('name' => '_policyid_static', 'value' => $_SESSION['amavis_pid'] ));
			//********** Userid Amavis
			$hidden_uid = new html_hiddenfield(array('name' => '_amavis_uid', 'value' => $_SESSION['amavis_uid'] ));		
					
			$table->add('title', html::label($field_id, Q(rcube_label('and-killlvl'))));
			$table->add(null, $hidden_policy->show() . $hidden_uid->show() . $hidden_spolicy->show() . $input_spamthres->show((float)$_SESSION['amavis_killlvl']));

			$table->add(array('colspan' => 2), Q(rcube_label('and-killlvl-exp')));
			$table->add_row();


			
			//********** Predefined Policy Levels

			$table->add(null, "&nbsp;");
			$table->add(null, "&nbsp;");

			$active_button = html::img(array('src' => $attrib['enableicon'], 'alt' => 'Set Active', 'border' => 0));
			$inactive_button = html::img(array('src' => $attrib['enableicon'], 'alt' => 'Set Active', 'border' => 0));
			
			$policy_table = new html_table(array('id' => 'spam-langs-table', 'class' => 'records-table', 'cellspacing' => '0', 'cols' => 4));
			$policy_table->add_header(array('width' => '150px'), 'Predefined Policy');
			$policy_table->add_header(array('width' => '25px'), 'Tag Level');
			$policy_table->add_header(array('width' => '25px'), 'Kill Level');
			$policy_table->add_header(array('width' => '40px'), '&nbsp;');
			$policy_table->add(array('id' => 'active_button'), $active_button);
			$policy_table->add(array('id' => 'inactive_button'), $inactive_button);	
			
			policy_row($policy_table, null, null, $del_button);
	
			$sql_result = $amavis_db->query("SELECT id,policy_name,spam_tag2_level,spam_kill_level FROM policy WHERE id < 8 AND id > 0 ORDER BY spam_tag2_level");
	
			if ($sql_result && $amavis_db->num_rows($sql_result) > 0)
				$norules = 'display: none;';
	
			$policy_table->set_row_attribs(array('style' => $norules));
			$policy_table->add(array('colspan' => '4'), rep_specialchars_output(rcube_label('noaddressrules')));
			$policy_table->add_row();
			$OUTPUT->set_env('address_rule_count', $amavis_db->num_rows());
			while ($sql_result && $sql_arr = $amavis_db->fetch_assoc($sql_result)) {
				$field = $sql_arr['id'];
				$value = $sql_arr['policy_name'];
				$tag = $sql_arr['spam_tag2_level'];
				$kill = $sql_arr['spam_kill_level'];
				policy_row($policy_table, $field, $value, $tag, $kill, $active_button, $inactive_button);
			}
			
			policy_row($policy_table, '5000', 'Custom Policy', '-', '-', $active_button, $inactive_button);
			
			$table->add(array('colspan' => 4), html::div(array('id' => 'address-rules-cont'), $policy_table->show()));
			$table->add_row();


		if ($table->size())
			$out = html::tag('fieldset', null, html::tag('legend', null, Q(rcube_label('spamgeneralsettings'))) . $table->show($attrib));

		break;


	// Address settings
	case 'addresses':
		$data = Q(rcube_label('and-whitelistwb')) . "<br /><br />";
		$data .= Q(rcube_label('and-whitelistpri')) . "<br /><br />";
		$data .= Q(rcube_label('and-whitelistexp')) . "<br /><br />";
		$enable_block = new html_hiddenfield(array('name' => '_do_addresses', 'value' => '1'));
		$data .= $enable_block->show();

		//if ($amavisdnewsql_config['whitelist_sync'])
		//	$data .= Q(rcube_label('autowhitelist')) . "<br /><br />";

		$table = new html_table(array('cols' => 4, 'width' => '100%'));
		$field_id = 'rcmfd_spamaddressrule';
		$input_spamaddressrule = new html_select(array('name' => '_spamaddressrule', 'id' => $field_id));
		$input_spamaddressrule->add('Whitelist','W');
		$input_spamaddressrule->add('Blacklist', 'B');

		//Add Priority
		$field_id = 'rcmfd_spamaddresspri';
		$input_spamaddresspri = new html_select(array('name' => '_spamaddressrulepri', 'id' => $field_id));
		$input_spamaddresspri->add('6','6');
		$input_spamaddresspri->add('7', '7');
		$input_spamaddresspri->add('8', '8');
		$input_spamaddresspri->add('9', '9');

		$field_id = 'rcmfd_spamaddress';
		$input_spamaddress = new html_inputfield(array('name' => '_spamaddress', 'id' => $field_id, 'style' => 'width:200px;'));

		$field_id = 'rcmbtn_add_address';
		$button_addaddress = new html_inputfield(array('type' => 'button', 'value' => rcube_label('addrule'), 'onclick' => 'addressrule_add()', 'id' => $field_id, 'class' => 'button', 'style' => 'width:75px;'));

		$table->add(null, $input_spamaddressrule->show());
		$table->add(null, $input_spamaddresspri->show());
		$table->add(null, $input_spamaddress->show());
		$table->add(array('align' => 'right'), $button_addaddress->show());
		$table->add(array('colspan' => 4), "&nbsp;");
		$table->add_row();

		if (!empty($attrib['deleteicon']))
			$del_button = html::img(array('src' => $RCMAIL->config->get('skin_path') . $attrib['deleteicon'], 'alt' => rcube_label('delete'), 'border' => 0));
		else
			$del_button = rcube_label('delete');

		$address_table = new html_table(array('id' => 'address-rules-table', 'class' => 'records-table', 'cellspacing' => '0', 'cols' => 4));
		$address_table->add_header(array('width' => '150px'), rcube_label('rule'));
		$address_table->add_header(array('width' => '60px'), 'Priority');
		$address_table->add_header(null, rcube_label('email'));
		$address_table->add_header(array('width' => '40px'), '&nbsp;');
		$cnt = 1;
		address_row($address_table, null, null, null, $cnt, $del_button);
		$cnt++;
		
		$sql = sprintf("SELECT wb,email,priority FROM wblist WHERE rid = '%d' order by reverse(email)", mysql_real_escape_string($_SESSION['amavis_uid']) );
		$sql_result = $amavis_db->query($sql);

		if ($sql_result && $amavis_db->num_rows($sql_result) > 0)
			$norules = 'display: none;';

		$address_table->set_row_attribs(array('style' => $norules));
		$address_table->add(array('colspan' => '4'), rep_specialchars_output(rcube_label('noaddressrules')));
		$address_table->add_row();
		$OUTPUT->set_env('address_rule_count', $amavis_db->num_rows());
		while ($sql_result && $sql_arr = $amavis_db->fetch_assoc($sql_result)) {
			$field = $sql_arr['wb'];
			$value = $sql_arr['email'];
			$priority = $sql_arr['priority'];
			address_row($address_table, $field, $value, $priority, $cnt, $del_button);
			$cnt++;
		}

		$table->add(array('colspan' => 4), html::div(array('id' => 'address-rules-cont'), $address_table->show()));
		$table->add_row();

		if ($table->size())
			$out = html::tag('fieldset', null, html::tag('legend', null, Q(rcube_label('and-spamaddressrules'))) . $data . $table->show($attrib));

		break;

	default:
		$out = '';
	}

	return $out;
}

function address_row($address_table, $field, $value, $priority, $cnt, $del_button) {
	if (!isset($field))
		$address_table->set_row_attribs(array('style' => 'display: none; '));
	else
		$address_table->set_row_attribs(array('style' => 'background-color:'.$fieldbg));

	$hidden_action = new html_hiddenfield(array('name' => '_address_rule_act[]', 'value' => ''));
	$hidden_field = new html_hiddenfield(array('name' => '_address_rule_field[]', 'value' => $field));
	$hidden_pri = new html_hiddenfield(array('name' => '_address_rule_pri[]', 'value' => $priority));
	$hidden_text = new html_hiddenfield(array('name' => '_address_rule_value[]', 'value' => $value));
		
	switch ($field) {
		case "W":
			$fieldtxt = rep_specialchars_output('Whitelist');
			$fieldbg = '#eeffbb';
			break;
		case "B":
			$fieldtxt = rep_specialchars_output('Blacklist');
			$fieldbg = '#bbbbbb';
			break;
	}
	
	if (isset($field))
		$address_table->set_row_attribs(array('style' => 'background-color:'.$fieldbg));
		
	$address_table->add(array('class' => $field), $fieldtxt);
  $address_table->add(array('class' => 'priority'), $priority);
	$address_table->add(array('class' => 'email'), $value);
	$address_table->add('control', '&nbsp;' . html::a(array('href' => "#", 'onclick' => 'return addressrule_del(this)', 'title' => rcube_label('delete')), $del_button) . $hidden_action->show() . $hidden_field->show() . $hidden_text->show() . $hidden_pri->show() );

	return $address_table;
}

function policy_row($policy_table, $field, $value, $tagnum, $killnum, $abtn, $iabtn){
	
	if (!isset($field))
		$policy_table->set_row_attribs(array('style' => 'display: none;'));
	
	if($_SESSION['amavis_pid'] == $field)
		$setbtn = $abtn;
	else
		$setbtn = '';

	if($_SESSION['amavis_pid'] > 7 && $field == '5000')
		$setbtn = $abtn;


	$hidden_action = new html_hiddenfield(array('name' => '_policy_tag['.$field.']', 'value' => $tagnum));
	$hidden_field = new html_hiddenfield(array('name' => '_policy_kill['.$field.']', 'value' => $killnum));
	$hidden_text = new html_hiddenfield(array('name' => '_policy_kill2['.$field.']', 'value' => $value));
	$hidden_uniq = new html_hiddenfield(array('name' => '_policy_uniq['.$field.']', 'value' => $tagnum.$killnum));
	
	$policy_table->add(array('class' => 'email'), "<A href=\"#\" onclick=\"return policy_set('".$field."')\">".$value."</a>" . $hidden_action->show() . $hidden_field->show() . $hidden_text->show() . $hidden_uniq->show() );
	$policy_table->add(array('class' => 'email'), $tagnum);
	$policy_table->add(array('class' => 'email'), $killnum);
	$policy_table->add('control', '&nbsp;' . html::a(array('href' => "#", 'id' => '_policy_ahref['.$field.']', 'title' => 'current policy'), $setbtn));

	return $policy_table;	
	
}


function valid_email($x){
		global $amavisdnewsql_config;
		
    if(preg_match('/^[_a-zA-Z0-9-]+(\.[_a-zA-Z0-9-]+)*@[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)+$/',$x)){
    	return $x;    	
	  }else{
	  	return $x . $amavisdnewsql_config['df_emaildomain'];
	  }
} 

?>